﻿using System.Collections.Generic;

namespace OpenBlock.ResourceManagement
{
    public class ResManager<TEntry>
    {
        public const char PATH_SEPARATOR = ':';

        private Dictionary<string, ushort> moduleMapId = new Dictionary<string, ushort>();
        private List<Module<TEntry>> modules = new List<Module<TEntry>>();

        public void AddModule(Module<TEntry> module)
        {
            moduleMapId.Add(module.Name, (ushort)modules.Count);
            modules.Add(module);
        }

        public void LoadModules()
        {
            foreach (var mod in modules)
            {
                mod.OnLoad();
            }
        }

        public ResRef? CreateRef(string path)
        {
            var (mod, res) = ParsePath(path);
            if (GetModuleId(mod) is ushort modId)
            {
                if (modules[modId].GetIndex(res) is ushort resId)
                {
                    return new ResRef
                    {
                        moduleId = modId,
                        resId = resId,
                    };
                }
            }
            return null;
        }

        public TEntry GetEntry(ResRef rr)
        {
            return GetModule(rr.moduleId).GetEntry(rr.resId);
        } 

        public ushort? GetModuleId(string name)
        {
            if (moduleMapId.TryGetValue(name, out ushort id)) return id;
            return null;
        }

        public Module<TEntry> GetModule(ushort id)
        {
            return modules[id];
        }

        public static (string, string) ParsePath(string path)
        {
            var sepIdx = path.IndexOf(PATH_SEPARATOR);

            if (sepIdx <= 0) throw new System.Exception($"Path:[{path}] must in a module");

            string moduleName = path.Substring(0, sepIdx);
            string resName = path.Substring(sepIdx + 1);

            return (moduleName, resName);
        }
    }
}
